<template>
    <div class="topic-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑标题' : '新增标题' }}</h2>
                </div>
                <div class="header-right">
                    <el-button @click="handleCancel">
                        <el-icon><ArrowLeft /></el-icon>
                        返回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
            <el-card shadow="never" class="form-card">
                <el-form
                    ref="topicFormRef"
                    :model="formData"
                    :rules="formRules"
                    label-width="120px"
                    class="topic-form"
                >
                    <!-- 中英文 -->
                    <el-form-item label="中英文:" prop="language">
                        <el-select v-model="formData.language" placeholder="请选择" style="width: 200px">
                            <el-option label="中文" value="zh-CN" />
                            <el-option label="英文" value="en" />
                        </el-select>
                    </el-form-item>

                    <!-- 标题 -->
                    <el-form-item label="标题:" prop="name">
                        <el-input
                            v-model="formData.name"
                            placeholder="输入标题"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <el-button type="primary" @click="handleSubmit">保存</el-button>
                        <el-button @click="handleCancel">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import { createTopicCategory, updateTopicCategory, getTopicCategoryById } from '@/api/content/topic-category';

const route = useRoute();
const router = useRouter();

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id);

// 表单引用
const topicFormRef = ref();

// 表单数据
const formData = reactive({
    language: '',
    name: ''
});

// 表单验证规则
const formRules = {
    language: [
        { required: true, message: '请选择语言', trigger: 'change' }
    ],
    name: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 1, max: 50, message: '标题长度在1-50个字符', trigger: 'blur' }
    ]
};

// 提交表单
const handleSubmit = async () => {
    try {
        await topicFormRef.value.validate();
        
        // 构建提交数据
        const submitData: any = {
            name: formData.name,
            i18nList: [
                {
                    language: formData.language,
                    name: formData.name,
                    imageUrl: '' // 先传空，按需求
                }
            ]
        };
        
        console.log('提交数据:', submitData);
        
        let res;
        if (isEdit.value) {
            // 编辑模式
            submitData.id = route.params.id as string;
            res = await updateTopicCategory(submitData);
        } else {
            // 新增模式
            res = await createTopicCategory(submitData);
        }
        
        const responseData = res as any;
        if (responseData && responseData.code === 200) {
            ElMessage.success(isEdit.value ? '编辑成功' : '新增成功');
            router.push('/topic-list');
        } else {
            const errorMsg = (responseData && responseData.msg) || (isEdit.value ? '编辑失败' : '新增失败');
            ElMessage.error(errorMsg);
        }
    } catch (error) {
        if (error !== false) { // 表单验证失败时 error 为 false
            console.error('提交失败:', error);
            ElMessage.error('操作失败，请稍后重试');
        }
    }
};

// 取消操作
const handleCancel = () => {
    ElMessageBox.confirm(
        '确定要离开吗？未保存的内容将丢失。',
        '确认离开',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        router.go(-1);
    }).catch(() => {
        // 用户取消
    });
};

// 加载话题分类详情
const loadTopicCategoryData = async (id: string) => {
    try {
        const res = await getTopicCategoryById(id);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200 && responseData.data) {
            const data = responseData.data;
            // const i18nData = data.i18nList && data.i18nList.length > 0 ? data.i18nList[0] : {};
            
            Object.assign(formData, {
                language: data.language || '',
                name: data.name || ''
            });
        } else {
            ElMessage.error('获取话题分类详情失败');
        }
    } catch (error) {
        console.error('加载话题分类数据失败:', error);
        ElMessage.error('网络错误，请稍后重试');
    }
};

// 页面初始化
onMounted(() => {
    if (isEdit.value) {
        // 编辑模式，加载数据
        const id = route.params.id as string;
        console.log('编辑模式，ID:', id);
        loadTopicCategoryData(id);
    }
});
</script>

<style scoped>
.topic-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

/* 表单内容 */
.form-card {
    border-radius: 8px;
}

.topic-form {
    padding: 20px;
}

.form-hint {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
    margin-left: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .topic-form-container {
        padding: 10px;
    }
    
    .form-content {
        max-width: 100%;
    }
    
    .topic-form {
        padding: 15px;
    }
}
</style>
